package com.workerhelping.controller;

import com.workerhelping.dto.PhoneNumDTO;
import com.workerhelping.result.Result;
import com.workerhelping.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class RedisController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 将验证码存入redis
     * @param key phoneNumber
     * @param value code
     * @return
     */
    @GetMapping("/sendMessage")
    public Result<Object> sendMessage(@RequestParam("key") String key,
                              @RequestParam("value") String value) {
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(key, value, 60, TimeUnit.MINUTES);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取验证码
     * @param phoneNumDTO
     * @return
     */
    @PostMapping("/getVerificationCode")
    public Result<String>  getVerificationCode(@RequestBody PhoneNumDTO phoneNumDTO) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String code = operations.get(phoneNumDTO.getPhoneNumber());
        if (StringUtils.isEmpty(code))
            return Result.build(null, ResultCodeEnum.REGISTER_CODE_ERROR);
        return Result.ok(code);
    }
}